﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using MakeIT.MiraPark.Negocios;

namespace MakeIT.MiraPark.Apresentacao
{
    public partial class FormCadastroObjeto : Form
    {
        private string operacao = "";

        public FormCadastroObjeto()
        {
            InitializeComponent();
        }

        private void FormCadastroObjeto_Load(object sender, EventArgs e)
        {
            //Popular a lista de objetos cadastrados
            this.dataGridViewPerfis.DataSource = ModelBO.getPerfis();
            this.dataGridViewUsuarios.DataSource = ModelBO.getUsuarios();
            this.dataGridViewObjetos.DataSource = ModelBO.getObjetos(true, true);

            this.panelUsuarios.Visible = false;
            this.panelPerfis.Visible = false;
            setupButtonsControls();
            timer1.Enabled=true;
        }

        private void dataGridViewObjetos_SelectionChanged(object sender, EventArgs e)
        {
            setupButtonsControls();
            setupUsuariosPerfis();
        }

        private void buttonNovo_Click(object sender, EventArgs e)
        {
            this.operacao = "novo";
            setupButtonsControls();
            setupUsuariosPerfis();
        }

        private void buttonCancelar_Click(object sender, EventArgs e)
        {
            this.operacao = "cancelar";
            setupButtonsControls();
            setupUsuariosPerfis();
        }

        private void buttonEditar_Click(object sender, EventArgs e)
        {
            this.operacao = "editar";
            setupButtonsControls();
        }

        private void buttonExcluir_Click(object sender, EventArgs e)
        {
            this.operacao = "excluir";

            List<ObjetoVO> objList = (List<ObjetoVO>)this.dataGridViewObjetos.DataSource;
            ObjetoVO obj = objList[this.dataGridViewObjetos.CurrentRow.Index];
            DialogResult dr = MessageBox.Show(this, "Confirma a exclusão do objeto " + obj.objeto, "Confirmação", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr.ToString().Equals("Yes"))
            {
                ModelBO.delPerfilXObjetos(obj.perfilxObjetoVOs);
                ModelBO.delUsuarioXObjetos(obj.usuarioXObjetoVOs);
                ModelBO.delObjeto(obj);

                int nRow = this.dataGridViewObjetos.CurrentRow.Index;
                this.dataGridViewObjetos.DataSource = ModelBO.getObjetos(true, true);
                if (this.dataGridViewObjetos.Rows.Count > 0)
                {
                    dataGridViewObjetos.CurrentCell = dataGridViewObjetos.Rows[Math.Min(nRow, this.dataGridViewObjetos.Rows.Count - 1)].Cells[1];
                    dataGridViewObjetos.Rows[Math.Min(nRow, this.dataGridViewObjetos.Rows.Count - 1)].Selected = true;
                }

                setupButtonsControls();
                setupUsuariosPerfis();
            }
        }

        private void buttonSalvar_Click(object sender, EventArgs e)
        {
            String erros = "";
            if (this.textBoxObjeto.Text.Trim().Length == 0)
                erros = erros + "Objeto deve ser informado.\r\n";
            if (this.textBoxDescricao.Text.Trim().Length == 0)
                erros = erros + "Descrição deve ser informado.\r\n";
            if (erros.Length > 0)
            {
                MessageBox.Show(this, erros, "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            ObjetoVO obj = null;

            if (this.operacao.Equals("novo"))
            {

                obj = ObjetoVO.CreateObjetoVO();
                obj.objeto = this.textBoxObjeto.Text;
                obj.descricao = this.textBoxDescricao.Text;

                obj.idObjeto = (int)ModelBO.newObjeto(obj);
            }
            if (this.operacao.Equals("editar"))
            {
                List<ObjetoVO> objList = (List<ObjetoVO>)this.dataGridViewObjetos.DataSource;
                obj = objList[this.dataGridViewObjetos.CurrentRow.Index];

                obj.objeto = this.textBoxObjeto.Text;
                obj.descricao = this.textBoxDescricao.Text;

                List<PerfilxObjetoVO> perfilxObjetoVOs = new List<PerfilxObjetoVO>();
                List<UsuarioxObjetoVO> usuarioxObjetoVOs = new List<UsuarioxObjetoVO>();

                int count = 0;
                foreach (UsuarioVO user in (List<UsuarioVO>)this.dataGridViewUsuarios.DataSource)
                {
                    if ((bool)this.dataGridViewUsuarios.Rows[count].Cells["usuarioxobjeto"].Value)
                    {
                        DataGridViewCellCollection dgvcc = this.dataGridViewUsuarios.Rows[count].Cells;
                        usuarioxObjetoVOs.Add(UsuarioxObjetoVO.CreateUsuarioxObjetoVO((int)dgvcc["idUsuario"].Value, obj.idObjeto, (bool)dgvcc["visivel"].Value, (bool)dgvcc["habilitado"].Value));
                    }
                    count++;
                }
                count = 0;
                foreach (PerfilVO perf in (List<PerfilVO>)this.dataGridViewPerfis.DataSource)
                {
                    DataGridViewCellCollection dgvcc = this.dataGridViewPerfis.Rows[count].Cells;
                   if (dgvcc["perfilxobjeto"].Value!=null && (bool)dgvcc["perfilxobjeto"].Value)
                    {
                        perfilxObjetoVOs.Add(PerfilxObjetoVO.CreatePerfilxObjetoVO((int)dgvcc["idPerfil"].Value, obj.idObjeto, (bool)dgvcc["visivelp"].Value, (bool)dgvcc["habilitadop"].Value));
                    }
                    count++;
                }

                ModelBO.delUsuarioXObjetos(obj.usuarioXObjetoVOs);
                ModelBO.newUsuarioXObjetos(usuarioxObjetoVOs);
                ModelBO.delPerfilXObjetos(obj.perfilxObjetoVOs);
                ModelBO.newPerfilXObjetos(perfilxObjetoVOs);
                ModelBO.setObjeto(obj);
            }
            this.operacao = "salvar";

            List<ObjetoVO> listObjetoVOs = ModelBO.getObjetos(true, true);
            dataGridViewObjetos.DataSource = listObjetoVOs;
            int nRow = listObjetoVOs.FindIndex(a => a.idObjeto == obj.idObjeto);
            dataGridViewObjetos.CurrentCell = dataGridViewObjetos.Rows[nRow].Cells[1];
            dataGridViewObjetos.Rows[nRow].Selected = true;

            setupUsuariosPerfis();
            setupButtonsControls();
        }

        private void setupUsuariosPerfis()
        {
            if (this.dataGridViewPerfis.CurrentRow != null){
                setupUsuariosPerfis(this.dataGridViewObjetos.CurrentRow.Index);
            }
        }
        private void setupUsuariosPerfis( int rowIndex)
        {

            List<ObjetoVO> objList = (List<ObjetoVO>)this.dataGridViewObjetos.DataSource;
            ObjetoVO obj = null;

            if (this.dataGridViewObjetos.CurrentRow == null || this.dataGridViewObjetos.RowCount == 0)
            {
                obj = ObjetoVO.CreateObjetoVO();
                obj.idObjeto = -1;
            }
            else{
                obj = objList[rowIndex];
            }

            if (this.dataGridViewObjetos.CurrentRow != null)
            {
                int count = 0;
                foreach (UsuarioVO user in (List<UsuarioVO>)this.dataGridViewUsuarios.DataSource)
                {
                    DataGridViewRow dgv = this.dataGridViewUsuarios.Rows[count];
                    UsuarioxObjetoVO usuarioxObjetoVO = UsuarioxObjetoVO.CreateUsuarioxObjetoVO(user.idUsuario, obj.idObjeto, false, false);

                    if ((!operacao.Equals("novo") && obj.usuarioXObjetoVOs.Contains(usuarioxObjetoVO, new UsuarioxObjetoVOComparer()))){
                        dgv.Cells["usuarioxobjeto"].Value = true;
                        usuarioxObjetoVO = obj.usuarioXObjetoVOs.Find(delegate(UsuarioxObjetoVO uxo) { return uxo.idObjeto == usuarioxObjetoVO.idObjeto; });
                        dgv.Cells["visivel"].Value = usuarioxObjetoVO.visivel;
                        dgv.Cells["habilitado"].Value = usuarioxObjetoVO.habilitado;
                    }
                    else
                    {
                        dgv.Cells["usuarioxobjeto"].Value = false;
                        dgv.Cells["visivel"].Value = false;
                        dgv.Cells["habilitado"].Value = false;
                    }

                    count++;
                }
                this.dataGridViewUsuarios.Refresh();

                count = 0;
                foreach (PerfilVO perf in (List<PerfilVO>)this.dataGridViewPerfis.DataSource)
                {
                    DataGridViewRow dgv = this.dataGridViewPerfis.Rows[count];
                    PerfilxObjetoVO perfilxObjetoVO = PerfilxObjetoVO.CreatePerfilxObjetoVO(perf.idPerfil, obj.idObjeto, false, false);

                    if (!operacao.Equals("novo") && obj.perfilxObjetoVOs.Contains(perfilxObjetoVO, new PerfilxObjetoVOComparer()))
                    {
                        dgv.Cells["perfilxobjeto"].Value = true;
                        perfilxObjetoVO = obj.perfilxObjetoVOs.Find(delegate(PerfilxObjetoVO uxo) { return uxo.idObjeto == perfilxObjetoVO.idObjeto; });
                        dgv.Cells["visivelp"].Value = perfilxObjetoVO.visivel;
                        dgv.Cells["habilitadop"].Value = perfilxObjetoVO.habilitado;
                    }
                    else
                    {
                        dgv.Cells["perfilxobjeto"].Value = false;
                        dgv.Cells["visivelp"].Value = false;
                        dgv.Cells["habilitadop"].Value = false;
                    }
                    count++;
                }
                this.dataGridViewPerfis.Refresh();
            }
        }

        private void setupButtonsControls()
        {
            bool haRows = this.dataGridViewObjetos.Rows.Count > 0 && this.dataGridViewObjetos.CurrentRow != null;
            bool novo = this.operacao.Equals("novo");
            bool edit = this.operacao.Equals("editar");
            bool canc = this.operacao.Equals("cancelar");

            this.radioButton2.Enabled = !novo;
            this.radioButton3.Enabled = !novo;

            this.buttonCancelar.Enabled = novo || edit;
            this.buttonNovo.Enabled = !novo && !edit;
            this.buttonEditar.Enabled = haRows && !novo && !edit;
            this.buttonExcluir.Enabled = haRows && !novo && !edit;
            this.buttonSalvar.Enabled = novo || edit;

            this.textBoxObjeto.Enabled = novo || edit;
            this.textBoxDescricao.Enabled = novo || edit;

            this.dataGridViewObjetos.Enabled = !novo && !edit;
            this.dataGridViewUsuarios.Columns["usuarioxobjeto"].ReadOnly = !edit;
            this.dataGridViewUsuarios.Columns["visivel"].ReadOnly = !edit;
            this.dataGridViewUsuarios.Columns["habilitado"].ReadOnly = !edit;
            this.dataGridViewPerfis.Columns["perfilxobjeto"].ReadOnly = !edit;
            this.dataGridViewPerfis.Columns["visivelp"].ReadOnly = !edit;
            this.dataGridViewPerfis.Columns["habilitadop"].ReadOnly = !edit;


            if (!haRows || novo)
            {
                this.textBoxId.Text = "";
                this.textBoxObjeto.Text = "";
                this.textBoxDescricao.Text = "";
            }
            else {
                List<ObjetoVO> objList = (List<ObjetoVO>)this.dataGridViewObjetos.DataSource;
                ObjetoVO obj = objList[this.dataGridViewObjetos.CurrentRow.Index];
                this.textBoxId.Text = obj.idObjeto.ToString();
                this.textBoxObjeto.Text = obj.objeto;
                this.textBoxDescricao.Text = obj.descricao;
            }
            if (novo || edit){
                this.textBoxObjeto.Focus();
            }
        }
        private void setupPanels(){
            this.panelCadastro.Visible = this.radioButton1.Checked;
            this.panelUsuarios.Visible = this.radioButton2.Checked;
            this.panelPerfis.Visible = this.radioButton3.Checked;
       }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            setupPanels();
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            setupPanels();
        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {
            setupPanels();
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            this.timer1.Enabled = false;
            setupUsuariosPerfis();
        }

     }
}
